﻿using DocumentFormat.OpenXml.Lite.Core.Interfaces;
using DocumentFormat.OpenXml.Lite.Core.Office;
using DocumentFormat.OpenXml.Lite.Shared;
using DocumentFormat.OpenXml.Lite.Xml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using IO = System.IO;

namespace DocumentFormat.OpenXml.Lite.SpreadsheetML.Drawing
{
    [XmlRoot("wsDr", Namespace = Constants.Drawing)]
    public class WorksheetDrawing : XmlSerializable, IOfficeElement, ISerializable
    {
        [XmlIgnore]
        public Guid DocumentId { get; set; }

        [XmlIgnore]
        public string RelationshipId { get; set; }

        [Optional]
        [XmlElement("", Namespace = Constants.Drawing)]
        public XmlList<ICellAnchor> CellAnchors { get; set; }

        [XmlNamespaceDeclarations]
        public XmlSerializerNamespaces Namespaces { get; set; }

        public WorksheetDrawing()
        {
            CellAnchors = new XmlList<ICellAnchor>();

            Namespaces = new XmlSerializerNamespaces();
            Namespaces.Add("a", Constants.Graphic);
            Namespaces.Add("xdr", Constants.Drawing);
            Namespaces.Add("r", Constants.Relationship);
        }

        public void AddNamespace(string prefix, string ns)
        {
            if (!Namespaces.ToArray().Any(n => n.Name == prefix && n.Namespace == ns))
            {
                Namespaces.Add(prefix, ns);
            }
        }

        public string CreateChartElement(IDrawingElement element)
        {
            return (DocumentManager.Instance.FindDocument(DocumentId)
                   as SpreadsheetDocument).CreateChartElementFor(this, element);
        }

        public string AddPicture(Image image)
        {
            return (DocumentManager.Instance.FindDocument(DocumentId)
                   as SpreadsheetDocument).CreatePictureElementFor(this, image);
        }

        public byte[] Serialize()
        {
            XmlSerializer serializer = new XmlSerializer(this.GetType());
            using (var stream = new IO.MemoryStream())
            {
                using (var writer = new IO.StreamWriter(stream, Encoding.UTF8))
                {
                    using (var xwriter = XmlWriter.Create(writer))
                    {
                        xwriter.WriteStartElement("xdr", "wsDr", Constants.Drawing);
                        foreach (var ns in Namespaces.ToArray())
                        {
                            if (ns.Name != "xdr")
                            {
                                xwriter.WriteAttributeString("xmlns", ns.Name, null, ns.Namespace);
                            }
                        }
                        this.WriteXml(xwriter);
                    }
                    return stream.ToArray();
                }
            }
        }

        public void Deserialize(System.IO.Stream content)
        {
            using (var reader = XmlReader.Create(content))
            {
                reader.ReadToDescendant("wsDr", Constants.Drawing);
                for (int i = 0; i < reader.AttributeCount; ++i)
                {
                    string s = reader.GetAttribute(i);
                    if (Constants.GetDefaultPrefix(s) != string.Empty)
                    {
                        Namespaces.Add(Constants.GetDefaultPrefix(s), s);
                    }
                }
                this.ReadXml(reader);
            }
        }
    }
}
